package jp.com.nobnak.commentviewer.live;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import jp.com.nobnak.commentviewer.common.IAction1;
import jp.com.nobnak.commentviewer.cookie.CookieUtil;
import jp.com.nobnak.commentviewer.net.AsyncRequest;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.webkit.CookieManager;

public class LiveStatusService {
	
	private final String mPlayerStatusUri;
	private final String mNicoLiveDomain;
	private final String mNicoLivePath;
	
	private List<IAction1<IResult>> mResultListeners = new LinkedList<IAction1<IResult>>();
	private List<IAction1<IError>> mErrorListeners = new LinkedList<IAction1<IError>>();
	
	public LiveStatusService(String domain, String path, String playerStatusUri) {
		mNicoLiveDomain = domain;
		mNicoLivePath = path;
		mPlayerStatusUri = playerStatusUri;
	}	

	public void send() {
		List<Cookie> cookies = CookieUtil.listCookies(CookieUtil.fromString(
				CookieManager.getInstance().getCookie(mPlayerStatusUri)),
				mNicoLiveDomain, mNicoLivePath);
		CookieStore store = new BasicCookieStore();
		for (Cookie cookie: cookies)
			store.addCookie(cookie);
		HttpContext context = new BasicHttpContext();
		context.setAttribute(ClientContext.COOKIE_STORE, store);
		HttpUriRequest getRequest = new HttpGet(mPlayerStatusUri);
		AsyncRequest request = new AsyncRequest(context, 
				new ResultHandler(new ResultListenerIterable()), 
				new ErrorHandler(new ErrorListenerIterable()));
		request.execute(getRequest);
	}
	
	public void listenResult(IAction1<IResult> listener) {
		mResultListeners.add(listener);
	}
	public void listenError(IAction1<IError> listener) {
		mErrorListeners.add(listener);
	}

	private class ResultListenerIterable implements Iterable<IAction1<IResult>> {
		@Override
		public Iterator<IAction1<IResult>> iterator() {
			return LiveStatusService.this.mResultListeners.iterator();
		}
	}
	private class ErrorListenerIterable implements Iterable<IAction1<IError>> {
		@Override
		public Iterator<IAction1<IError>> iterator() {
			return LiveStatusService.this.mErrorListeners.iterator();
		}
	}
}
